package com.sharing.config;

import com.sharing.service.MyUserDetailsService;
import com.sharing.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;
import java.io.UnsupportedEncodingException;

/**
 * @author MingTian
 * @version 1.0
 * @description TODO
 * @date 2023/4/4 15:25
 */
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyUserDetailsService userDetailService;
//    @Bean
//    public BCryptPasswordEncoder passwordEncoder() {
//        return new BCryptPasswordEncoder();
//    }

    //认证用户的来源
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        auth.userDetailsService(userDetailService).passwordEncoder(new BCryptPasswordEncoder());

        auth.userDetailsService(userDetailService).passwordEncoder(new PasswordEncoder(){

            @Override
            public String encode(CharSequence rawPassword) {
                try {
                    return MD5Util.encode((String)rawPassword);
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                }
            }

            @Override
            public boolean matches(CharSequence rawPassword, String encodedPassword) {
                try {
                    return encodedPassword.equals(MD5Util.encode((String)rawPassword));
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                }
            }}); //user Details Service验证
    }

    @Autowired
    private DataSource dataSource;

    /**
     * 自动登录配置————注入数据源，配置操作数据库对象
     * @return
     */
    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);
//        jdbcTokenRepository.setCreateTableOnStartup(true);

        return jdbcTokenRepository;
    }

    //配置SpringSecurity相关信息
    @Override
    public void configure(HttpSecurity http) throws Exception {
        // 用户退出配置
        http.logout().logoutUrl("/logout").logoutSuccessUrl("/user/logout").permitAll();

        http.formLogin()   // 登录页面设置
                .loginPage("/login.html").permitAll()
                .loginProcessingUrl("/user/login") // 登录访问路径
                .defaultSuccessUrl("/success.html").permitAll() // 登录成功之后，跳转路径
                .and().authorizeRequests()
                .antMatchers("/", "/user/login", "/login", "/productionlike/*", "/productionlike", "/user",
                        "/comment", "/comment/mult", "/comment/parentComment", "/comment/topParentComment",
                        "/comment/topProduction", "/userProduction", "/browseRecord/user", "/browseRecord", "/browseRecord/ids",
                        "/productionHobby/production", "/hobby/first", "/hobby/second", "/hobby",
                        "/userStatistics/userRegistrationNumbers").permitAll() // 设置那些路径可以直接访问，不需要认证
//                .antMatchers("/base").hasAnyAuthority("管理用户")
                .anyRequest().authenticated()
                .and().rememberMe().tokenRepository(persistentTokenRepository())
                .tokenValiditySeconds(60) // 设置有效时长，单位秒
                .userDetailsService(userDetailService)
                .and().csrf().disable();  // 管不csrf防护

//        http.csrf().disable()  //关闭csrf
//                .addFilter(new JwtLoginFilter(super.authenticationManager(),rsaKeyProperties))
//                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);    //禁用session
    }
}
